package com.ccteam.fluidmusic.ui.local

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.ccteam.fluidmusic.core.TaglibParser
import com.ccteam.fluidmusic.databinding.FragmentLocalMusicPagerBinding
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.fluidmusic.ui.PARENT_ID_KEY
import com.ccteam.fluidmusic.ui.local.LocalMusicViewModel.Companion.RESCAN_NONE
import com.ccteam.fluidmusic.ui.local.more.LocalMusicMoreBottomSheetFragmentDirections
import com.ccteam.fluidmusic.view.adapters.GlobalDefaultMusicItemAdapter
import com.ccteam.fluidmusic.view.base.LightBounceEdgeEffectFactory
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.view.bean.MoreInfoData
import com.ccteam.model.Resource
import com.ccteam.shared.result.music.DefaultMusicItem
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/1/7
 *
 * 本地歌曲页面显示
 * 与 [LocalMusicViewModel] 联动
 * 显示本地歌曲的列表信息
 * 此Fragment显示在 [ViewPager] 中
 */
@AndroidEntryPoint
class LocalMusicPagerFragment : Fragment() {

    private lateinit var parentId: String

    private var _binding: FragmentLocalMusicPagerBinding? = null
    private val binding get() = _binding!!

    private val localMusicViewModel by viewModels<LocalMusicViewModel>(ownerProducer = { parentFragment ?: this })

    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    @Inject lateinit var lightBounceEdgeEffectFactory: LightBounceEdgeEffectFactory

    @Inject lateinit var taglibParser: TaglibParser

    /**
     * 是否为第一次加载
     */
    private var isFirstLoad: Boolean = true

    private val defaultMusicItemClickCallback = object:
        GlobalDefaultMusicItemAdapter.DefaultMusicItemClickCallback {

        override fun musicItemClicked(item: DefaultMusicItem) {
            mainActivityViewModel.playMediaId(item.mediaId,parentId,true)
        }

        override fun moreClicked(item: DefaultMusicItem) {
            findNavController().navigate(
                LocalMusicMoreBottomSheetFragmentDirections.actionLocalMoreBottomSheet(
                    MoreInfoData(
                        parentId, item.mediaId, item.title, item.subtitle, true, null,
                        emptyList(), item.albumArtUri, mediaUri = item.mediaUri
                    )
                )
            )
        }
    }

    private val adapter = GlobalDefaultMusicItemAdapter(defaultMusicItemClickCallback)

    companion object {
        @JvmStatic
        fun newInstance(parentId: String): LocalMusicPagerFragment {
            return LocalMusicPagerFragment().apply {
                arguments = Bundle().apply {
                    putString(PARENT_ID_KEY, parentId)
                }
            }
        }
    }

    /**
     * 由于 ViewPager2 特性，当该Fragment被显示时才会被调用
     * 此时我们可以进行数据的懒加载操作
     */
    override fun onResume() {
        super.onResume()
        if(isFirstLoad){
            observeMusicItems()
            isFirstLoad = false
        }
    }

    /**
     * 由于ViewPager2的原因，如果大量数据直接放在 [onViewCreated] 中
     * 会导致在滑动时就进行数据填充，导致动画卡顿
     * 所以我们将其放在 [onResume] 中
     */
    private fun observeMusicItems(){
        // 观察列表变化，有变化则提交，如果处于加载中，则显示进度条
        localMusicViewModel.musicItems.observe(viewLifecycleOwner, {
            if(it is Resource.Success){
                adapter.submitList(it.data)
            }
        })

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLocalMusicPagerBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        parentId = arguments?.getString(PARENT_ID_KEY) ?: return

        lightBounceEdgeEffectFactory.applyBounceView(binding.rvLocalMusicPagerList,this)
        binding.rvLocalMusicPagerList.edgeEffectFactory = lightBounceEdgeEffectFactory

        binding.rvLocalMusicPagerList.adapter = adapter

        localMusicViewModel.rescanStatusByTab.observe(viewLifecycleOwner, {
            // 如果当前parentId处于未扫描状态，则开始订阅，否则不订阅，防止重复订阅
            if(it[parentId] == RESCAN_NONE){
                // 订阅前显示进度条
                binding.statusView.changeToLoadingStatus(true)
                localMusicViewModel.subscribeByChildrenParentId(parentId)
            }
        })

        localMusicViewModel.musicLoadMessage.observe(viewLifecycleOwner, {
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
        })

    }

    override fun onDestroyView() {
        super.onDestroyView()

        // 摧毁View后将重新进行第一次加载
        isFirstLoad = true
        _binding = null
    }
}